import { defineStore } from "pinia";
import { ref, computed, shallowReactive } from "vue";
import type { FileSystemItem, ClipboardData } from "../types/fileSystem";
import { fileSystemData } from "../data";
import { useCachedComputed, clearComputedCache } from "../hooks/usePerformance";
import { performanceMonitor } from "../utils/performanceMonitor";

export const useFileStore = defineStore("file", () => {
  // 状态
  const currentPath = ref("/C:/Users/Administrator/Desktop");
  const history = ref(["/C:/Users/Administrator/Desktop"]);
  const historyIndex = ref(0);
  const selectedItem = ref<FileSystemItem | null>(null);
  const viewMode = ref<"list" | "grid">("grid");

  // 拖拽状态
  const dragOverItem = ref<FileSystemItem | null>(null);
  const draggedItem = ref<FileSystemItem | null>(null);

  // 剪贴板状态
  const clipboard = ref<ClipboardData>({
    item: null,
    operation: null,
  });

  // 文件系统数据（浅层响应式，提升性能）
  const fileSystem = shallowReactive(fileSystemData);

  // 排序状态
  const sortField = ref<string>("name");
  const sortOrder = ref<"asc" | "desc">("asc");

  // 计算属性
  const pathParts = computed(() => {
    return currentPath.value.split("/").filter(part => part !== "");
  });

  const currentItems = useCachedComputed(
    () => {
      const items = fileSystem[currentPath.value] || [];
      return sortItems(items);
    },
    "currentItems",
    [currentPath.value, sortField.value, sortOrder.value]
  );

  const canGoBack = computed(() => historyIndex.value > 0);
  const canGoForward = computed(
    () => historyIndex.value < history.value.length - 1
  );
  const canGoUp = computed(() => currentPath.value !== "/");

  // 排序缓存，提升性能
  const sortCache = ref<Map<string, FileSystemItem[]>>(new Map());

  // 生成缓存键
  const getSortCacheKey = (
    path: string,
    field: string,
    order: string
  ): string => {
    return `${path}|${field}|${order}`;
  };

  // 优化后的排序方法，添加缓存机制和性能监控
  const sortItems = (items?: FileSystemItem[]) => {
    return performanceMonitor.measure("sortItems", () => {
      const itemsToSort = items || fileSystem[currentPath.value] || [];

      // 生成缓存键
      const cacheKey = getSortCacheKey(
        currentPath.value,
        sortField.value,
        sortOrder.value
      );

      // 检查缓存
      if (sortCache.value.has(cacheKey) && !items) {
        return sortCache.value.get(cacheKey)!;
      }

      const sorted = [...itemsToSort].sort((a, b) => {
        let aValue: any;
        let bValue: any;

        switch (sortField.value) {
          case "name":
            aValue = a.name.toLowerCase();
            bValue = b.name.toLowerCase();
            break;
          case "lastModified":
            aValue = a.lastModified.getTime();
            bValue = b.lastModified.getTime();
            break;
          case "size":
            aValue = a.size || 0;
            bValue = b.size || 0;
            break;
          default:
            aValue = a.name.toLowerCase();
            bValue = b.name.toLowerCase();
        }

        // 文件夹总是排在前面（除非按大小排序）
        if (sortField.value !== "size") {
          if (a.type === "folder" && b.type !== "folder") return -1;
          if (a.type !== "folder" && b.type === "folder") return 1;
        }

        let result = 0;
        if (aValue < bValue) result = -1;
        else if (aValue > bValue) result = 1;

        return sortOrder.value === "asc" ? result : -result;
      });

      // 缓存结果（如果不是自定义 items）
      if (!items) {
        sortCache.value.set(cacheKey, sorted);
      }

      return sorted;
    });
  };

  // 清除排序缓存的辅助方法
  const clearSortCache = () => {
    sortCache.value.clear();
    // 同时清除计算属性缓存
    clearComputedCache("currentItems");
  };

  // Actions
  const navigate = (path: string) => {
    if (fileSystem[path] !== undefined) {
      currentPath.value = path;
      selectedItem.value = null;

      // 清除排序缓存，因为路径变化了
      clearSortCache();

      // 更新历史记录
      if (historyIndex.value < history.value.length - 1) {
        history.value = history.value.slice(0, historyIndex.value + 1);
      }
      history.value.push(path);
      historyIndex.value = history.value.length - 1;
    }
  };

  const navigateToIndex = (index: number) => {
    const parts = currentPath.value.split("/").filter(part => part !== "");
    if (index === 0) {
      navigate("/");
    } else {
      const newPath = "/" + parts.slice(0, index).join("/");
      navigate(newPath);
    }
  };

  const goBack = () => {
    if (canGoBack.value) {
      historyIndex.value--;
      currentPath.value = history.value[historyIndex.value];
      selectedItem.value = null;
    }
  };

  const goForward = () => {
    if (canGoForward.value) {
      historyIndex.value++;
      currentPath.value = history.value[historyIndex.value];
      selectedItem.value = null;
    }
  };

  const goUp = () => {
    if (canGoUp.value) {
      const parts = currentPath.value.split("/").filter(part => part !== "");
      if (parts.length > 0) {
        parts.pop();
        const newPath = parts.length > 0 ? "/" + parts.join("/") : "/";
        navigate(newPath);
      }
    }
  };

  const setViewMode = (mode: "list" | "grid") => {
    viewMode.value = mode;
  };

  const selectItem = (item: FileSystemItem | null) => {
    selectedItem.value = item;
  };

  const clearSelection = () => {
    selectedItem.value = null;
  };

  // 文件操作
  const createNewFolder = () => {
    const newFolder: FileSystemItem = {
      name: "新建文件夹",
      type: "folder",
      lastModified: new Date(),
    };

    if (!fileSystem[currentPath.value]) {
      fileSystem[currentPath.value] = [];
    }
    fileSystem[currentPath.value].push(newFolder);
    // 清除缓存，因为数据变化了
    clearSortCache();
  };

  const createNewFile = () => {
    const newFile: FileSystemItem = {
      name: "新建文本文档.txt",
      type: "file",
      size: 0,
      extension: "txt",
      lastModified: new Date(),
    };

    if (!fileSystem[currentPath.value]) {
      fileSystem[currentPath.value] = [];
    }
    fileSystem[currentPath.value].push(newFile);
    // 清除缓存，因为数据变化了
    clearSortCache();
  };

  const deleteItem = (item?: FileSystemItem) => {
    const targetItem = item || selectedItem.value;
    if (!targetItem) return;

    const currentItemsArray = fileSystem[currentPath.value];
    if (currentItemsArray) {
      const index = currentItemsArray.findIndex(
        (i: FileSystemItem) => i.name === targetItem.name
      );
      if (index > -1) {
        currentItemsArray.splice(index, 1);
        if (selectedItem.value === targetItem) {
          selectedItem.value = null;
        }
        // 清除缓存，因为数据变化了
        clearSortCache();
      }
    }
  };

  const copyToClipboard = (item?: FileSystemItem) => {
    const targetItem = item || selectedItem.value;
    if (targetItem) {
      clipboard.value = {
        item: { ...targetItem },
        operation: "copy",
        sourcePath: currentPath.value,
      };
    }
  };

  const cutToClipboard = (item?: FileSystemItem) => {
    const targetItem = item || selectedItem.value;
    if (targetItem) {
      clipboard.value = {
        item: { ...targetItem },
        operation: "cut",
        sourcePath: currentPath.value,
      };
    }
  };

  const pasteFromClipboard = () => {
    if (clipboard.value.item && clipboard.value.operation) {
      const item = clipboard.value.item;
      const operation = clipboard.value.operation;
      const sourcePath = clipboard.value.sourcePath;

      if (!fileSystem[currentPath.value]) {
        fileSystem[currentPath.value] = [];
      }

      // 检查是否在同一路径下操作
      const isSamePath = sourcePath === currentPath.value;

      if (operation === "copy") {
        // 复制操作：生成唯一的副本名称
        let newName = isSamePath ? `${item.name} - 副本` : item.name;
        let counter = 1;

        // 检查名称冲突并生成唯一名称
        while (
          fileSystem[currentPath.value].some(
            (existingItem: FileSystemItem) => existingItem.name === newName
          )
        ) {
          if (isSamePath) {
            newName = `${item.name} - 副本(${counter})`;
          } else {
            newName = `${item.name}(${counter})`;
          }
          counter++;
        }

        const newItem = {
          ...item,
          id: Math.random().toString(36).substr(2, 9),
          name: newName,
        };
        fileSystem[currentPath.value].push(newItem);

        // 清除缓存，因为数据变化了
        clearSortCache();

        // 复制操作完成后，清空剪贴板（不需要重复粘贴）
        clipboard.value = {
          item: null,
          operation: null,
          sourcePath: undefined,
        };
      } else if (operation === "cut") {
        // 剪切操作：从源路径删除，添加到目标路径
        if (sourcePath && sourcePath !== currentPath.value) {
          // 从源路径删除
          const sourceItems = fileSystem[sourcePath];
          if (sourceItems) {
            const sourceIndex = sourceItems.findIndex(
              (i: FileSystemItem) => i.name === item.name
            );
            if (sourceIndex > -1) {
              sourceItems.splice(sourceIndex, 1);
            }
          }

          // 检查目标路径是否有同名文件
          let newName = item.name;
          let counter = 1;
          while (
            fileSystem[currentPath.value].some(
              (existingItem: FileSystemItem) => existingItem.name === newName
            )
          ) {
            const nameParts = item.name.split(".");
            if (nameParts.length > 1 && item.type === "file") {
              // 文件：在扩展名前添加数字
              const extension = nameParts.pop();
              const baseName = nameParts.join(".");
              newName = `${baseName}(${counter}).${extension}`;
            } else {
              // 文件夹：直接添加数字
              newName = `${item.name}(${counter})`;
            }
            counter++;
          }

          // 添加到目标路径
          const movedItem = { ...item, name: newName };
          fileSystem[currentPath.value].push(movedItem);

          // 清除缓存，因为数据变化了
          clearSortCache();

          // 清空剪贴板
          clipboard.value = {
            item: null,
            operation: null,
            sourcePath: undefined,
          };
        } else if (sourcePath === currentPath.value) {
          // 在同一路径下剪切粘贴，不做任何操作
          return;
        }
      }
    }
  };

  const clearClipboard = () => {
    clipboard.value = {
      item: null,
      operation: null,
      sourcePath: undefined,
    };
  };

  return {
    // State
    currentPath,
    history,
    historyIndex,
    selectedItem,
    viewMode,
    dragOverItem,
    draggedItem,
    clipboard,
    fileSystem,
    sortField,
    sortOrder,

    // Computed
    pathParts,
    currentItems,
    canGoBack,
    canGoForward,
    canGoUp,

    // Actions
    navigate,
    navigateToIndex,
    goBack,
    goForward,
    goUp,
    setViewMode,
    selectItem,
    clearSelection,
    createNewFolder,
    createNewFile,
    deleteItem,
    copyToClipboard,
    cutToClipboard,
    pasteFromClipboard,
    clearClipboard,
    sortItems,
  };
});
